import { useCallback } from "react";
import { URLSearchParamsInit, useSearchParams } from "react-router-dom";
import { pureObject, isFalsy } from "utils";

export const useSetUrlSearchParam = () => {
  const [searchParams, setSearchParams] = useSearchParams();
  return useCallback(
    (param: Partial<Record<string, unknown>>) => {
      const o = pureObject(
        { ...Object.fromEntries(searchParams), ...param },
        isFalsy
      ) as URLSearchParamsInit;
      return setSearchParams(o);
    },
    [searchParams, setSearchParams]
  );
};
